var tools = require('../../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

var controller = require(tools.rootPath + 'libs/controller.js');
var fs = require('fs');
//沙箱包
//https://www.npmjs.com/package/wechat-pay
var Payment = require(tools.rootPath + 'wechat-pay').Payment;

module.exports = class extends controller {
    constructor() {
        super();
    }
    //https://www.appblog.cn/2020/01/13/%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98%E6%B2%99%E7%AE%B1%E6%B5%8B%E8%AF%95%E9%87%87%E5%9D%91%E8%AE%B0%E5%BD%95/
    /*
微信支付验收阶段可以用沙盒测试支付流程

文档：https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=23_1

基本步骤
正式请求地址修改，增加/sandboxnew/
按正式流程做sign
用正式sign，额外调用 https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey 获得sandbox_signkey
用sandbox_signkey 替换用户自己的key，再做sign签名
用第二次生成的sign来掉起支付
发起支付的瞬间就会有回调通知，生成的二维码并不能用
遇到的问题
（1）沙箱验证签名失败，请确认沙箱签名key是否正确

解决：使用sandbox_signkey替换的是用户设定的key值

（2）沙箱支付金额(xxx)无效，请检查需要验收的case

解决：金额只能是 101 和 102（单位为分）
    */
    /*
wx.chooseWXPay({
   timestamp: 0, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
   nonceStr: '', // 支付签名随机串，不长于 32 位
   package: '', // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
   signType: '', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
   paySign: '', // 支付签名
   success: function (res) {
     // 支付成功后的回调函数
   }
 });
    */
    //点击购买按钮->发送post请求到/home/pay/index创建订单并生成支付参数,前台调用wx.chooseWXPay用户输入密码进行支付
    //微信服务器发送异步post到http://szh.free.idcfengye.com/payment/car修改订单状态
    //car part
    async index(req, res) {
        //https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=23_1&index=2
        let initConfig = Object.assign({ ...config.wechatPay }, { notifyUrl: 'http://szh.free.idcfengye.com/payment/car' });
        let p = new Payment(initConfig);
        let signkey = await p.getsignkey();
        initConfig.partnerKey = signkey.sandbox_signkey;
        let p2 = new Payment(initConfig);
        let order = {
            body: '吮指原味鸡 * 1',
            attach: '{"部位":"三角"}',
            out_trade_no: 'kfc' + (+new Date),
            total_fee: 101,
            spbill_create_ip: '127.0.0.1',
            openid: 'oC5lY1Z6uukn0OGyAhTzCTz0CklQ',
            trade_type: 'JSAPI',
        };
        let payargs = await p2.getBrandWCPayRequestParams(order);
        console.log(payargs);
        return 'ok';
    }
    //house part
    async index2(req, res) {
        //https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=23_1&index=2
        let initConfig = Object.assign({ ...config.wechatPay }, { notifyUrl: 'http://szh.free.idcfengye.com/payment/house' });
        let p = new Payment(initConfig);
        let signkey = await p.getsignkey();
        initConfig.partnerKey = signkey.sandbox_signkey;
        let p2 = new Payment(initConfig);
        let order = {
            body: '吮指原味鸡 * 2',
            attach: '{"部位":"四角"}',
            out_trade_no: 'kfc' + (+new Date),
            total_fee: 102,
            spbill_create_ip: '127.0.0.1',
            openid: 'oC5lY1Z6uukn0OGyAhTzCTz0CklQ',
            trade_type: 'JSAPI',
        };
        let payargs = await p2.getBrandWCPayRequestParams(order);
        console.log(payargs);
        return 'ok';
    }
    //查询订单
    /*
{
  openid: 'wxd930ea5d5a258f4f',
  sub_mch_id: '',
  coupon_fee: '3',
  cash_fee_type: 'CNY',
  settlement_total_fee: '100',
  nonce_str: 'ddygysnGzA6gcldw9ljwOELhxDjAODcR',
  return_code: 'SUCCESS',
  err_code_des: 'SUCCESS',
  time_end: '20201201143317',
  mch_id: '1497328512',
  trade_type: 'JSAPI',
  trade_state_desc: 'ok',
  trade_state: 'SUCCESS',
  coupon_batch_id_1: '6789',
  coupon_batch_id_0: '12345',
  sign: '8305B80C76B6AB030C65019793648FB1',
  cash_fee: '99',
  coupon_id_1: '10001',
  coupon_type_0: 'CASH',
  coupon_id_0: '10000',
  coupon_fee_0: '1',
  coupon_fee_1: '2',
  is_subscribe: 'Y',
  return_msg: 'OK',
  fee_type: 'CNY',
  bank_type: 'CMC',
  attach: 'sandbox_attach',
  device_info: 'sandbox',
  out_trade_no: 'kfc1606803624098',
  coupon_type_1: 'NO_CASH',
  transaction_id: '4560275659820201201142025799655',
  total_fee: '102',
  appid: '',
  coupon_count: '2',
  result_code: 'SUCCESS',
  err_code: 'SUCCESS'
}
    */
    async check(req, res) {
        let initConfig = Object.assign({ ...config.wechatPay });
        let p = new Payment(initConfig);
        let signkey = await p.getsignkey();
        initConfig.partnerKey = signkey.sandbox_signkey;
        let p2 = new Payment(initConfig);
        try {
            let order = await p2.orderQuery({
                //transaction_id: '4560275659820201201142025799655',
                out_trade_no: 'kfc1606803624098',
            });
            console.log(order);
        } catch (e) {
            console.log(e);
        }

        return 'ok';
    }


}